﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Hardcodet.Wpf.TaskbarNotification;
using Microsoft.Win32;
using Snap.Api;
using Snap.Api.Imgur;
using Snap.Capture;
using Snap.Extensions;
using Application = System.Windows.Application;
using Clipboard = System.Windows.Clipboard;

namespace Snap
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public bool DoExplicitelyClose { get; set; }
        private ApiBase imageUploadApi;

        public MainWindow()
        {
            InitializeComponent();

            this.Hide();
            Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;

            imageUploadApi = new ImgurApi();

            HotKey printScreenHotKey = new HotKey(Key.PrintScreen, KeyModifier.None, OnPrintScreen, true);
            HotKey altPrintScreenHotKey = new HotKey(Key.PrintScreen, KeyModifier.Alt, OnAltPrintScreen, true);
        }

        public void OnPrintScreen(HotKey hotKey)
        {
            CaptureScreen(new Rect(new Size(SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight)));
        }

        public void OnAltPrintScreen(HotKey hotKey)
        {
            CaptureScreen(WinApiFunctions.GetActiveWindowDimensions());
        }

        public void CaptureScreen(Rect area)
        {
            var bitmapSource = GdiCapture.CaptureScreen(area);

            BitmapEncoder bitmapEncoder = null;

            if (Setting_ImageFormat.Text == "PNG")
            {
                bitmapEncoder = new PngBitmapEncoder();
            }
            else if (Setting_ImageFormat.Text == "JPEG")
            {
                bitmapEncoder = new JpegBitmapEncoder();
                (bitmapEncoder as JpegBitmapEncoder).QualityLevel = (int)Setting_ImageQuality.Value;
            }

            var bitmapFrame = BitmapFrame.Create(bitmapSource);
            bitmapEncoder.Frames.Add(bitmapFrame);

            Stream stream;

            if (Setting_DoSaveCaptures.IsChecked.Value)
            {
                stream = File.Open(Setting_CaptureDirectory.Text + "\\" + new DateTime().GetTimeStampToday() + "." + Setting_ImageFormat.Text, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);
            }
            else
            {
                stream = new MemoryStream();
            }

            bitmapEncoder.Save(stream);


            var memoryStream = new MemoryStream();
            stream.Position = 0;
            stream.CopyTo(memoryStream);
            byte[] imageBytes = memoryStream.ToArray();

            stream.Close();

            ApiResponseBase response = imageUploadApi.UploadSnapshot(imageBytes);

            for (int i = 0; i < 10; i++)
            {
                try
                {
                    Clipboard.SetText(response.Link);
                    break;
                }
                catch { }
                System.Threading.Thread.Sleep(1);
            }

            MyNotifyIcon.ShowBalloonTip("Snap", "Link copied to clipboard!", BalloonIcon.Info);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);

            if (!DoExplicitelyClose)
            {
                e.Cancel = true;
                this.Hide();
            }
        }

        private void MenuItem_Configure_Click(object sender, RoutedEventArgs e)
        {
            this.Show();
        }

        private void MenuItem_Exit_Click(object sender, RoutedEventArgs e)
        {
            DoExplicitelyClose = true;
            Application.Current.Shutdown();
        }

        private void Setting_BrowseCaptureDirectory_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            DialogResult result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                Setting_CaptureDirectory.Text = dialog.SelectedPath;
            }
        }
    }
}
